package main

import (
	"changeme/pkg"
	"context"
	"fmt"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"log"
	"os"
	"path"
	"strings"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called at application startup
func (a *App) startup(ctx context.Context) {
	// Perform your setup here
	a.ctx = ctx
}

// domReady is called after front-end resources have been loaded
func (a App) domReady(ctx context.Context) {
	// Add your action here
}

// beforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
// Returning true will cause the application to continue, false will continue shutdown as normal.
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
	return false
}

// shutdown is called at application termination
func (a *App) shutdown(ctx context.Context) {
	// Perform your teardown here
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

func (a *App) SelectFile() (res pkg.Response) {
	var selectFile pkg.SelectFile
	opt := runtime.OpenDialogOptions{
		Filters: []runtime.FileFilter{
			{
				Pattern: "*.xlsx",
			},
		},
	}
	dialog, err := runtime.OpenFileDialog(a.ctx, opt)
	if err != nil {
		log.Println("选择文件失败，", err)
	}
	if dialog == "" {
		// 未选择文件
		res.Code = 2 // 不处理结果
		return res
	}
	dialog = strings.ReplaceAll(dialog, "\\", "/")
	// 判断文件类型
	if path.Ext(dialog) != ".xlsx" {
		res.Code = 1 // 错误
		res.Msg = "文件类型不支持，仅支持.xlsx文件"
		return
	}
	// 读取excel
	titles, err := pkg.ReadTitles(dialog)
	if err != nil {
		res.Msg = err.Error()
		res.Code = 1
		return
	}
	selectFile = pkg.SelectFile{
		Filename: path.Base(dialog),
		FilePath: dialog,
		Titles:   titles,
	}
	res.Data = selectFile
	return res
}

func (a *App) DivideFile(readPath string, key int, prefix string) (res pkg.Response) {
	log.Println(readPath, key)
	// 保存文件
	opt := runtime.SaveDialogOptions{
		Filters: []runtime.FileFilter{
			{
				DisplayName: "文件名",
				Pattern:     ".xlsx",
			},
		},
	}
	filename, err := runtime.SaveFileDialog(a.ctx, opt)
	if err != nil {
		res.Code = 1
		res.Msg = err.Error()
		return
	}
	if filename == "" {
		// 没有选择文件
		res.Code = 1
		res.Msg = "请设置要保存的文件"
		return
	}
	// 检测文件是否存在
	_, err = os.Stat(filename + ".xlsx")
	if err == nil {
		res.Code = 1
		res.Msg = "该文件名已存在，请重新设置"
		return
	}
	go func() {
		// 处理excel
		err := pkg.ReadAndSaveFile(readPath, filename+".xlsx", key, prefix)
		res := pkg.Response{
			Data: filename + ".xlsx",
		}
		if err != nil {
			res.Code = 1
			res.Msg = err.Error()
		}
		runtime.EventsEmit(a.ctx, "saveSuccess", res)
	}()
	return
}
